import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../providers/comic_provider.dart';
import '../../providers/auth_provider.dart'; // 使用新的认证Provider
import '../../utils/auth_utils.dart';
import '../../widgets/login_dialog.dart';

// 删除重复的Provider定义
// final isLoggedInProvider = StateProvider<bool>((ref) => false);
// final userEmailProvider = StateProvider<String>((ref) => 'user_123919143@qq.com');

class ProfileScreen extends ConsumerWidget {
  const ProfileScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final authState = ref.watch(authProvider);
    final isLoggedIn = authState.isLoggedIn;
    String userEmail = authState.userInfo?.nickname ?? "";

    if (authState.userInfo?.email == '923919143@qq.com') {
      userEmail = "Tourists0034";
    }

    return Scaffold(
      backgroundColor: const Color.fromRGBO(33, 24, 57, 1),
      appBar: AppBar(
        centerTitle: false,
        backgroundColor: const Color(0xFF211839),
        elevation: 0,
        systemOverlayStyle: const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarIconBrightness: Brightness.light,
          statusBarBrightness: Brightness.dark,
        ),
        title: Text(
          isLoggedIn ? userEmail : 'Not logged in',
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
            color: Color(0xFFE8E8F0),
          ),
        ),
        actions: [
          IconButton(
              onPressed: () {
                AuthUtils.showCustomerServiceDialog(context);
              },
              icon: const Icon(
                Icons.support_agent,
                color: Color(0xFFE8E8F0),
                size: 20,
              ))
        ],
      ),
      body: SafeArea(
        child: Column(
          children: [
            // 顶部用户信息区域
            Container(
              padding: const EdgeInsets.all(20),
              child: Column(
                children: [
                  // 第二行：头像、皇冠和LOGIN按钮
                  Row(
                    children: [
                      // 用户头像
                      CircleAvatar(
                        radius: 30,
                        backgroundImage: authState.userInfo?.avatar != null &&
                                authState.userInfo!.avatar!.isNotEmpty
                            ? CachedNetworkImageProvider(
                                authState.userInfo!.avatar!,
                              )
                            : null,
                        child: authState.userInfo?.avatar == null ||
                                authState.userInfo!.avatar!.isEmpty
                            ? const Icon(Icons.people_sharp, size: 30)
                            : null,
                      ),

                      const SizedBox(width: 16),

                      // 皇冠图标
                      if (authState.userInfo?.isSubscribe == true)
                        Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: const Color(0xFF2D3748), // 深色背景
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: const Icon(
                            Icons.star,
                            color: Color(0xFFECC94B), // 金色
                            size: 24,
                          ),
                        ),

                      const Spacer(),

                      // LOGIN按钮（仅未登录时显示）
                      if (!isLoggedIn)
                        GestureDetector(
                          onTap: () {
                            // 显示登录对话框而不是直接设置登录状态
                            showDialog(
                              context: context,
                              barrierDismissible: false,
                              builder: (context) => const LoginDialog(),
                            );
                          },
                          child: Container(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 20, vertical: 10),
                            decoration: BoxDecoration(
                              border:
                                  Border.all(color: const Color(0xFF4A5568)),
                              borderRadius: BorderRadius.circular(20),
                              color: const Color(0xFF2D3748),
                            ),
                            child: const Text(
                              'LOGIN',
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w500,
                                color: Color(0xFFE8E8F0),
                              ),
                            ),
                          ),
                        ),
                    ],
                  ),
                ],
              ),
            ),

            // Premium卡片
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 20),
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 18),
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    Color(0xFF667EEA), // 蓝紫色渐变
                    Color(0xFF764BA2),
                  ],
                ),
                borderRadius: BorderRadius.circular(16),
                boxShadow: [
                  BoxShadow(
                    color: const Color(0xFF667EEA).withOpacity(0.3),
                    blurRadius: 12,
                    offset: const Offset(0, 6),
                  ),
                ],
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          'JOIN Premium',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            letterSpacing: 0.5,
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          'Unlimited Reading Comics',
                          style: TextStyle(
                            color: Colors.white.withOpacity(0.8),
                            fontSize: 12,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ],
                    ),
                  ),
                  // 钻石图标
                  Container(
                    margin: const EdgeInsets.only(right: 12),
                    child: _buildDiamondIcon(),
                  ),
                  // Buy Now按钮
                  GestureDetector(
                    onTap: () {
                      // 处理购买逻辑
                      if (context.mounted) {
                        final container = ProviderScope.containerOf(context);
                        container.read(bottomNavIndexProvider.notifier).state =
                            2;
                      }
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 18, vertical: 10),
                      decoration: BoxDecoration(
                        gradient: const LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: [
                            Color(0xFFECC94B), // 金色渐变
                            Color(0xFFD69E2E),
                          ],
                        ),
                        borderRadius: BorderRadius.circular(20),
                        boxShadow: [
                          BoxShadow(
                            color: const Color(0xFFECC94B).withOpacity(0.4),
                            blurRadius: 6,
                            offset: const Offset(0, 3),
                          ),
                        ],
                      ),
                      child: const Text(
                        'Buy Now',
                        style: TextStyle(
                          color: Color(0xFF1A202C),
                          fontSize: 14,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 20),

            // Wallet和Daily卡片
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Row(
                children: [
                  // Wallet卡片
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        if (isLoggedIn) {
                          GoRouter.of(context).pushNamed('topup');
                        } else {
                          showDialog(
                            context: context,
                            barrierDismissible: false,
                            builder: (context) => const LoginDialog(),
                          );
                        }
                      },
                      child: Container(
                        height: 100,
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          gradient: const LinearGradient(
                            begin: Alignment.topLeft,
                            end: Alignment.bottomRight,
                            colors: [
                              Color(0xFFED8936), // 橙色渐变
                              Color(0xFFDD6B20),
                            ],
                          ),
                          borderRadius: BorderRadius.circular(12),
                          boxShadow: [
                            BoxShadow(
                              color: const Color(0xFFED8936).withOpacity(0.3),
                              blurRadius: 8,
                              offset: const Offset(0, 4),
                            ),
                          ],
                        ),
                        child: Stack(
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Text(
                                  'Wallet',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                                const SizedBox(height: 4),
                                Text(
                                  'Gems recharge',
                                  style: TextStyle(
                                    color: Colors.white.withOpacity(0.8),
                                    fontSize: 12,
                                  ),
                                ),
                              ],
                            ),
                            Positioned(
                              bottom: 0,
                              right: 0,
                              child: Icon(
                                Icons.account_balance_wallet,
                                color: Colors.white.withOpacity(0.7),
                                size: 40,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),

                  const SizedBox(width: 12),

                  // Daily卡片
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        if (isLoggedIn) {
                          GoRouter.of(context).pushNamed('daily-checkin');
                        } else {
                          showDialog(
                            context: context,
                            barrierDismissible: false,
                            builder: (context) => const LoginDialog(),
                          );
                        }
                        // 处理每日签到功能
                      },
                      child: Container(
                        height: 100,
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          gradient: const LinearGradient(
                            begin: Alignment.topLeft,
                            end: Alignment.bottomRight,
                            colors: [
                              Color(0xFF9F7AEA), // 紫色渐变
                              Color(0xFF805AD5),
                            ],
                          ),
                          borderRadius: BorderRadius.circular(12),
                          boxShadow: [
                            BoxShadow(
                              color: const Color(0xFF9F7AEA).withOpacity(0.3),
                              blurRadius: 8,
                              offset: const Offset(0, 4),
                            ),
                          ],
                        ),
                        child: Stack(
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Text(
                                  'Daily',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                                const SizedBox(height: 4),
                                Text(
                                  '7 days in row',
                                  style: TextStyle(
                                    color: Colors.white.withOpacity(0.8),
                                    fontSize: 12,
                                  ),
                                ),
                              ],
                            ),
                            Positioned(
                              bottom: 0,
                              right: 0,
                              child: Icon(
                                Icons.card_giftcard,
                                color: Colors.white.withOpacity(0.7),
                                size: 40,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 30),

            // Feedback和Settings菜单项
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 20),
              decoration: BoxDecoration(
                color: const Color(0xFF30244c), // 深色背景
                borderRadius: BorderRadius.circular(12),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.2),
                    blurRadius: 10,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              child: Column(
                children: [
                  _buildMenuItem(
                    context: context,
                    ref: ref,
                    icon: Icons.feedback_outlined,
                    iconColor: const Color(0xFF8f77c4), // 蓝色
                    title: 'Feedback',
                    onTap: () {
                      GoRouter.of(context).pushNamed('feedback');
                    },
                  ),
                  Container(
                    margin: const EdgeInsets.symmetric(horizontal: 16),
                    height: 1,
                    color: const Color(0xFF30244c), // 分割线颜色
                  ),
                  _buildMenuItem(
                    context: context,
                    ref: ref,
                    icon: Icons.settings_outlined,
                    iconColor: const Color(0xFF8f77c4), // 绿色
                    title: 'Settings',
                    onTap: () {
                      GoRouter.of(context).pushNamed('settings');
                    },
                  ),
                ],
              ),
            ),

            const Spacer(),
          ],
        ),
      ),
    );
  }

  Widget _buildMenuItem({
    required BuildContext context,
    required WidgetRef ref,
    required IconData icon,
    required Color iconColor,
    required String title,
    required VoidCallback onTap,
  }) {
    return ListTile(
      contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
      leading: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          color: const Color(0xFF30244c),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Icon(
          icon,
          size: 20,
          color: iconColor,
        ),
      ),
      title: Text(
        title,
        style: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w500,
          color: Color(0xFFE8E8F0), // 浅色文字
        ),
      ),
      trailing: const Icon(
        Icons.chevron_right,
        color: Color(0xFFA0AEC0), // 中性灰色
        size: 22,
      ),
      onTap: onTap,
    );
  }

  Widget _buildDiamondIcon() {
    return Container(
      width: 45,
      height: 45,
      child: CustomPaint(
        painter: DiamondPainter(),
      ),
    );
  }
}

class DiamondPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..style = PaintingStyle.fill
      ..shader = LinearGradient(
        begin: Alignment.topLeft,
        end: Alignment.bottomRight,
        colors: [
          const Color(0xFFECC94B), // 金色渐变
          const Color(0xFFD69E2E),
          const Color(0xFFB7791F),
        ],
        stops: const [0.0, 0.5, 1.0],
      ).createShader(Rect.fromLTWH(0, 0, size.width, size.height));

    final path = Path();
    final centerX = size.width / 2;
    final centerY = size.height / 2;

    // 创建钻石形状
    path.moveTo(centerX, 5); // 顶点
    path.lineTo(centerX + 15, centerY - 5); // 右上
    path.lineTo(centerX + 12, size.height - 8); // 右下
    path.lineTo(centerX, size.height - 2); // 底点
    path.lineTo(centerX - 12, size.height - 8); // 左下
    path.lineTo(centerX - 15, centerY - 5); // 左上
    path.close();

    canvas.drawPath(path, paint);

    // 添加高光效果
    final highlightPaint = Paint()
      ..style = PaintingStyle.fill
      ..color = Colors.white.withOpacity(0.4);

    final highlightPath = Path();
    highlightPath.moveTo(centerX, 5);
    highlightPath.lineTo(centerX + 15, centerY - 5);
    highlightPath.lineTo(centerX + 8, centerY);
    highlightPath.lineTo(centerX - 8, centerY);
    highlightPath.lineTo(centerX - 15, centerY - 5);
    highlightPath.close();

    canvas.drawPath(highlightPath, highlightPaint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}
